package com.assets.lease;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.assets.Adapter.Input_Adapter_item1;
import com.assets.BaseActivity;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.Scan.qrcode.util.Constant;
import com.assets.Scan.zxing.activity.CaptureActivity;
import com.assets.bean.Input_item1;
import com.assets.newNHF.util.LogUtils;
import com.assets.util.MyRFIDHandle;
import com.assets.util.RFIDClientUtil;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Lease_add extends BaseActivity implements OnDismissListener {
    private EditText leaseholder;//租赁人
    private String url = "http://" + Url.IP + "/api/leaseAddInspect";
    private String up_url = "http://" + Url.IP + "/api/leaseAdd";
    private EditText leasing_amount;//租赁金额
    private TextView duration;//租赁时长
    private EditText Lease_note, et_num;//租赁备注，扫码
    private LinearLayout Date;
    private String id;//登录id
    private List<String> numbers = new ArrayList<>();//资产ID
    private List<Input_item1> data = new ArrayList<>();
    private List<String> rfid_data = new ArrayList<>();
    private List<String> lv_data = new ArrayList<>();//判断是否重复
    private Lease_add content;
    private ListView lv_list;
    private ImageView fh;
    private Handler handler = new Handler();
    private Button rfid_bt, upload_bt, scan_img;
    private RFIDClientUtil rfidClientUtil;
    private Map<String, String> map = new HashMap<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        content = this;
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id", "");
        lv_data.clear();
        data.clear();
    }

    @Override
    public int intiLayout() {
        return R.layout.lease_add;
    }

    @Override
    public void initView() {
        fh = (ImageView) findViewById(R.id.fh);
        lv_list = (ListView) findViewById(R.id.fragment2_list);
        rfid_bt = (Button) findViewById(R.id.Rfid);
        upload_bt = (Button) findViewById(R.id.upload);
        scan_img = (Button) findViewById(R.id.scan_img);
        leaseholder = (EditText) findViewById(R.id.leaseholder);
        leasing_amount = (EditText) findViewById(R.id.leasing_amount);
        duration = (TextView) findViewById(R.id.duration);
        Lease_note = (EditText) findViewById(R.id.remark);
        Date = (LinearLayout) findViewById(R.id.date);
        et_num = (EditText) findViewById(R.id.et_num);
        lv_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                showTipDialog(aBoolean -> {
                    if (aBoolean) {
//                        lv_data.remove(data.get(position).getCode_number());
                        data.remove(position);
                        Input_Adapter_item1 adapter_item = new Input_Adapter_item1(content, R.layout.input_adapter_item, data);
                        lv_list.setAdapter(adapter_item);
                    }
                }, "确认删除");
                return true;
            }
        });
        initRFID();
    }

    @Override
    public void initData() {
        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable S) {
                et_num.selectAll();
                for (int i = 0; i < data.size(); i++) {
//                    if (S.equals(data.get(i).getCode_number())) {
//                        Toast.makeText(content, "该资产已存在列表", Toast.LENGTH_SHORT).show();
//                        return;
//                    }
                }
                if (!et_num.getText().toString().trim().equals("") && et_num.length() > 9) {
                    if (!lv_data.contains(et_num.getText().toString().trim())) {
                        post(et_num.getText().toString().trim(), "");
                    } else {
                        showToast("此资产已存在列表");
                    }

                } else {
                    showToast("错误的格式");
                }
            }
        });
        fh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final DatePickDialog dialog = new DatePickDialog(Lease_add.this);
                //设置上下年分限制
                dialog.setYearLimt(20);
                //设置标题
                dialog.setTitle("选择时间");
                //设置类型
                dialog.setType(DateType.TYPE_ALL);
                //设置消息体的显示格式，日期格式
                dialog.setMessageFormat("yyyy-MM-dd HH:mm");
                //设置选择回调
                dialog.setOnChangeLisener(null);
                //设置点击确定按钮回调
                dialog.setOnSureLisener(new OnSureLisener() {
                    @Override
                    public void onSure(java.util.Date date) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String time = sdf.format(date);
                        duration.setText(time);
                    }
                });
                dialog.show();

            }
        });
        upload_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        scan_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQrCode();
            }
        });
        rfid_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String rfidTitle = rfid_bt.getText().toString();
                if (rfidTitle.equals("开始读取")) {
                    rfidClientUtil.read();
                } else {
                    rfidClientUtil.stop();
                }
            }
        });
        upload_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (data.size() <= 0) {
                    showToast("请添加资产");
                    return;
                }
                if (leaseholder.getText().toString().trim().equals("") || leasing_amount.getText().toString().trim().equals("") || duration.getText().toString().equals("")) {
                    showToast("请完善数据后重试！");
                    return;
                }
                new AlertView(" 提示！", "是否上传数据", "取消", new String[]{"确定"}, null, content, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position == 0) {
                            numbers.clear();
                            for (int i = 0; i < data.size(); i++) {
//                                numbers.add(data.get(i).getCode_number());
                            }
                            updata();
                        }
                        if (position == -1) {

                        }

                    }
                }).setCancelable(true).setOnDismissListener(Lease_add.this).show();

            }
        });


    }

    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(content, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent datas) {
        super.onActivityResult(requestCode, resultCode, datas);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = datas.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            for (int i = 0; i < data.size(); i++) {
//                if (scanResult.equals(data.get(i).getCode_number())) {
//                    Toast.makeText(content, "该资产已存在列表", Toast.LENGTH_SHORT).show();
//                    return;
//                }
            }
            if (!lv_data.contains(scanResult)) {
                post(scanResult, "");
            } else Toast.makeText(content, "该资产已存在列表", Toast.LENGTH_SHORT).show();

        }
    }

    public void post(final String assetNumber, final String rfid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient
                        .Builder()
                        .hostnameVerifier(new AllowAllHostnameVerifier())
                        .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                        .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                        .readTimeout(500, TimeUnit.SECONDS)
                        .build();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("assetNumber", assetNumber)
                        .add("rfid", rfid); //传递键值对参数
                Request request = new Request.Builder()//创建Request 对象。
                        .url(url)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        Log.i("123123", "error");
                        if (!TextUtils.isEmpty(rfid)) {
                            Lease_add.this.map.remove(rfid);
                        }
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject json = new JSONObject(responseData);
                                    String state = json.getString("state");
                                    if (state.equals("1")) {
                                        JSONObject jsonObject = json.getJSONObject("asset");
                                        String assetName = jsonObject.getString("assetName");
                                        String deptId = jsonObject.getString("deptId");
                                        String assetNumber = jsonObject.getString("assetNumber");
                                        if (lv_data.contains(assetNumber)) {
                                            showToast("该资产已存在列表");
                                            return;
                                        }
                                        lv_data.add(assetNumber);
                                        String userId = jsonObject.getString("userId");
                                        String model = jsonObject.getString("model");
                                        String type = jsonObject.getString("type");
                                        String rfid = jsonObject.getString("rfid");
                                        String image = "";
                                        if (!TextUtils.isEmpty(jsonObject.getString("image"))) {
                                            image = "http://" + Url.IP + jsonObject.getString("image");
                                        }
//                                        data.add(0, new Input_item1(image, assetName, deptId, assetNumber, userId, model, type, rfid));
                                        Input_Adapter_item1 adapter_item = new Input_Adapter_item1(content, R.layout.input_adapter_item, data);
                                        lv_list.setAdapter(adapter_item);
                                        Toast.makeText(content, "添加成功", Toast.LENGTH_SHORT).show();
                                    }
                                    if (state.equals("0")) {
                                        Toast.makeText(content, "添加失败，请检查服务器", Toast.LENGTH_SHORT).show();
                                    }
                                    if (state.equals("2")) {
                                        Toast.makeText(content, "添加失败，此资产不存在", Toast.LENGTH_SHORT).show();
                                    }
                                    if (state.equals("3")) {
                                        Toast.makeText(content, "添加失败，资产已租用", Toast.LENGTH_SHORT).show();
                                    }
                                    if (state.equals("4")) {
                                        Toast.makeText(content, "添加失败，非闲置资产", Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                    }
                });

            }
        }).start();

    }

    private void initRFID() {
        MyRFIDHandle myRFIDHandle = new MyRFIDHandle();
        myRFIDHandle.post(() -> {
            rfidClientUtil = new RFIDClientUtil(epc -> {
                if (map.containsKey(epc)) {
                    return;
                }
                map.put(epc, "");
                LogUtils.d(epc);
                post("", epc);
            });
            rfidClientUtil.setRequestStop(() -> runOnUiThread(() -> {
                rfid_bt.setText("开始读取");
            }));
            rfidClientUtil.setRequestRead(() -> runOnUiThread(() -> {
                rfid_bt.setText("停止读取");
            }));
            getLifecycle().addObserver(myRFIDHandle);
            getLifecycle().addObserver(rfidClientUtil);
        });
    }


    private void updata() {
        new Thread() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient
                            .Builder()
                            .hostnameVerifier(new AllowAllHostnameVerifier())
                            .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                            .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                            .readTimeout(500, TimeUnit.SECONDS)
                            .build();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("userId", Since_case.getInstance().getUserId())
                            .add("leaseUser", leaseholder.getText().toString().trim())
                            .add("leaseTime", duration.getText().toString())
                            .add("leaseAmount", leasing_amount.getText().toString().trim())
                            .add("leaseRemark", Lease_note.getText().toString().trim())
                            .add("assetNumbers", numbers.toString())
                            .build();
                    Request request = new Request.Builder()
                            .url(up_url)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void showResponse(final String responseData) {
        try {
            JSONObject jsonObject = new JSONObject(responseData);
            if (jsonObject.getString("state").equals("1")) {
                showToast("提交成功");
                finish();
            } else {
                showToast("提交失败,请重新提交");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDismiss(Object o) {

    }


}
